local skynet = require "skynet"

local s = require "service"
local player_factory = require "agent_mgr_player"

require "agent_mgr_def"


s.players = {}

s.resp.login = function(source, uid, node, gate)
    local player = s.players[uid]
    if player and player:get_status() == STATUS.LOGIN then
        skynet.error("login fail, at status LOGIN, uid: " .. uid)
        return false
    end
    if player and player:get_status() == STATUS.LOGOUT then
        skynet.error("login fail, at status LOGOUT, uid: " .. uid)
        return false
    end

    -- 顶号, 旧设备踢下线
    if player then
        player:set_status(STATUS.LOGOUT)
        -- 踢掉gate
        s.call(player:get_node(), player:get_gate(), "kick", uid)
        -- 踢掉agent
        s.call(player:get_node(), player:get_agent(), "kick")
        s.send(player:get_node(), player:get_agent(), "exit")
        s.players[uid] = nil
    end

    -- 新设备上线
    player = player_factory.new()
    player:set_uid(uid)
    player:set_node(node)
    player:set_gate(gate)
    player:set_status(STATUS.LOGIN)
    s.players[uid] = player
    -- TODO: 优化agent pool
    local agent = skynet.newservice("agent", "agent", uid)
    player:set_agent(agent)
    player:set_status(STATUS.GAME)

    return true, agent
end

s.resp.kick = function(source, uid, reason)
    local player = s.players[uid]
    if not player then
        return false
    end

    if player:get_status() ~= STATUS.GAME then
        return false
    end

    player:set_status(STATUS.LOGOUT)
    s.call(player:get_node(), player:get_agent(), "kick")
    s.send(player:get_node(), player:get_agent(), "exit")
    s.players[uid] = nil

    return true
end


s.start(...)